import 'package:kq_flutter_widgets/widgets/sectionListView/secion_index_model/kq_section_index_group_model.dart';
import 'package:lpinyin/lpinyin.dart';

import 'index_config.dart';
import 'kq_section_index_model.dart';

class KqSectionIndexState<T> {
  ///是否需要排序，默认需要
  bool isSort;

  KqSectionIndexState({this.isSort = true});

  List<KqSectionIndexGroupModel<T>> sectionList = [];

  ///初始化分区
  initSectionList() {
    sectionList = [];
    for (int i = 0; i < IndexConfig.indexList.length; i++) {
      KqSectionIndexGroupModel<T> model = KqSectionIndexGroupModel();
      model.sectionKey = IndexConfig.indexList[i];
      model.recordList = [];
      sectionList.add(model);
    }
    KqSectionIndexGroupModel<T> info = KqSectionIndexGroupModel();
    info.sectionKey = "#";
    info.recordList = [];
    sectionList.add(info);
  }

  ///获取当前真实的分区内容
  List<String> getIndexList(List<KqSectionIndexGroupModel> list) {
    List<String> array = [];
    for (int i = 0; i < list.length; i++) {
      KqSectionIndexGroupModel model = list[i];
      if (model.recordList!.isNotEmpty) {
        array.add(model.sectionKey ?? '');
      }
    }
    return array;
  }

  ///重组网络请求下来的数据
  List<KqSectionIndexGroupModel<T>> recombinationDataScore(List data) {
    initSectionList();
    for (int i = 0; i < data.length; i++) {
      String firstName = '';
      KqSectionIndexModel model = data[i] as KqSectionIndexModel;
      firstName = PinyinHelper.getPinyin(model.name()).toUpperCase();
      model.namePy = firstName;
      String firstChar = firstName[0];
      int index = IndexConfig.indexList.indexOf(firstChar);
      KqSectionIndexGroupModel<T> info;
      if (index == -1) {
        info = sectionList.last;
      } else {
        info = sectionList[index];
      }
      info.recordList!.add(model as T);
    }
    return removeNullList(sectionList);
  }

  ///剔除没有数据的分区
  List<KqSectionIndexGroupModel<T>> removeNullList(List list) {
    List<KqSectionIndexGroupModel<T>> data = [];
    for (int i = 0; i < list.length; i++) {
      KqSectionIndexGroupModel<T> model = list[i];
      if (model.recordList!.isNotEmpty) {
        if (isSort) {
          KqSectionIndexGroupModel<KqSectionIndexModel> info =
              model as KqSectionIndexGroupModel<KqSectionIndexModel>;
          info.recordList!.sort(
              (KqSectionIndexModel a, KqSectionIndexModel b) =>
                  a.namePy!.compareTo(b.namePy!));
        }

        data.add(model);
      }
    }
    return data;
  }
}
